# coding:utf-8

# 请克隆本工程，
# 进入根目录：source venv/bin/activate
# 执行 pip install requests

import requests
import sys
import os
from xml.dom.minidom import parse
import xml.etree.ElementTree as ET
from google_trans_new import google_translator
from constant import DEFAULT_SERVICE_URLS, LANGUAGES
import sys
import uuid
import requests
import hashlib
import time
from imp import reload
import time
reload(sys)

YOUDAO_URL = 'https://openapi.youdao.com/api'
APP_KEY = '46fc6ef9361f9ed7'
APP_SECRET = 'rPu4SQzHj3YElmxbC2lJSTqIhUzVaKsy'


def encrypt(signStr):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()


def truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]

def do_request(data):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    return requests.post(YOUDAO_URL, data=data, headers=headers)

def translate_youdao(text, lang):
    data = {}
    data['from'] = 'zh'
    data['to'] = lang
    data['signType'] = 'v3'
    curtime = str(int(time.time()))
    data['curtime'] = curtime
    salt = str(uuid.uuid1())
    signStr = APP_KEY + truncate(text) + salt + curtime + APP_SECRET
    sign = encrypt(signStr)
    data['appKey'] = APP_KEY
    data['q'] = text
    data['salt'] = salt
    data['sign'] = sign

    response = do_request(data)
    json = response.json()
    source_text = json['query']
    result_text = json['translation'][0]
    return result_text

def translate_google(text, lang):
    translator = google_translator()  
    translate_text = translator.translate(text,lang_src = 'zh', lang_tgt=lang)    
    return translate_text

# Google 语言代码：https://cloud.google.com/translate/docs/languages?hl=zh-cn
# 有道语言代码：   https://reurl.cc/52Myon
trans_map_google = {
    "values": "en",             # 英语
    "values-de": "de",          # 德语
    "values-es": "es",          # 西班牙语
    "values-fr": "fr",          # 法语
    "values-it": "it",          # 意大利语
    "values-ja": "ja",          # 日语
    "values-ko": "ko",          # 韩语
    "values-pl": "pl",          # 波兰语
    "values-pt": "pt",          # 葡萄牙语
    "values-ru": "ru",          # 俄语
    "values-th": "th",          # 泰文
    "values-tr": "tr",          # 土耳其语
    "values-vi": "vi",          # 越南语
    "values-ar": "ar",          # 阿拉伯语
    "values-zh": " zh",         # 简体中文
    "values-zh-rHK": "zh-TW",   # 繁体中文
    "values-zh-rTW": "zh-TW",   # 繁体中文
}

trans_map_name = {
    "values": "英语",             # 英语
    "values-de": "德语",          # 德语
    "values-es": "西班牙语",          # 西班牙语
    "values-fr": "法语",          # 法语
    "values-it": "意大利语",          # 意大利语
    "values-ja": "日语",          # 日语
    "values-ko": "韩语",          # 韩语
    "values-pl": "波兰语",          # 波兰语
    "values-pt": "葡萄牙语",          # 葡萄牙语
    "values-ru": "俄语",          # 俄语
    "values-th": "泰文",          # 泰文
    "values-tr": "土耳其语",          # 土耳其语
    "values-vi": "越南语",          # 越南语
    "values-ar": "阿拉伯语",          # 阿拉伯语
    "values-zh": "简体中文",         # 简体中文
    "values-zh-rHK": "繁体中文",   # 繁体中文
    "values-zh-rTW": "繁体中文",   # 繁体中文
}

# 翻译函数：繁体用谷歌，其他用有道
def translate(text, lang):
    if (lang == "zh-TW"):
        return translate_google(text, lang)
    else:
        return translate_youdao(text, lang)

#print '参数列表:', str(sys.argv)

# 工程的资源根目录，这个要用参数传进来
root_dir = "appbase_custom/src/main/res"
source_txt = "translate_source.txt"
# 使用 三个等号分割
split_str = "==="

print("\n >>>>>> 开始执行脚本...")

if (os.path.exists(source_txt) == False):
    print("\n >>>>>> " + source_txt + "已经创建好了，请参照示例添加要翻译的中文！")
    f = open(source_txt, "w")
    f.write("this_is_string_key===这个是对应的中文--仅供参考，请删除此行\n")
    f.close()
    sys.exit(1)

print("\n >>>>>> 找到了 " + source_txt + " 文件")

if (os.path.exists(root_dir) == False):
    print(source_txt + "res目录不存在！")
    sys.exit(1)

print("\n >>>>>> 找到了 " + root_dir + " 目录")

# 首先检查文件格式
index = 0
file = open(source_txt)
for eachLine in file:
    found = eachLine.find(split_str)
    if (found == -1):
        print("注意！文件格式不符合要求！未包含 \"" + split_str + "\" 分割符号，或者是一个空行！\n请检查第 " + str(index + 1) + " 行")
        sys.exit(1)
    index = index + 1

print("\n >>>>>> " + source_txt + " 文件内部格式检验通过")

print("\n >>>>>> 开始逐个翻译")

index = 0
file = open(source_txt)
for eachLine in file:
    splits = eachLine.split(split_str)
    key = splits[0].strip()
    value = splits[1].strip()
    if key == "this_is_string_key":
        print(" >>>>>>     跳过示例: " + value)
        continue
    print(" >>>>>>     翻译语句: " + value)
    for file in os.listdir(root_dir):
        file_path = root_dir + "/" + file + "/strings.xml"
        if (os.path.exists(file_path)):
            with open(file_path, "r") as f:
                all_xml_lines = f.readlines()
            with open(file_path, "w") as f:                                
                for xml_line in all_xml_lines:
                    if xml_line.strip("\n") != "</resources>":
                        f.write(xml_line) 
                ret = ""
                if (file == "values-zh"):
                    ret = value.strip().strip("\n")       
                else:
                    ret = translate(value, trans_map_google[file]).strip()
                ret = ret.replace("\'", "\\'")
                ret = ret.replace("\"", "\\\"")                       
                xml_content = "\n    <string name=\"" + key + "\">" + ret + "</string>"              
                print(" >>>>>>             " + trans_map_name[file] + "=" + ret)
                f.write(xml_content)
                f.write("\n</resources>")        

print("\n >>>>>> 翻译完成，请检查Git的本地改动记录，若无误则提交")










